<script lang="ts" setup>
import { ref, onActivated, onDeactivated } from 'vue';
import { Carousel } from '@ark-ui/vue/carousel';
import { useFetch } from '@/mobile/hooks/fetch';
import { useAsyncData } from '@/mobile/hooks/async-data';

const { $fetch } = useFetch();

const { data: imgList } = useAsyncData(
  'home:banner',
  () => $fetch('/operator/getOperatorList', { method: 'post', data: { operateType: 2 } }),
);

// 默认值需要使用 -1 否则 Carousel.Indicator 渲染不正常
const index = ref(-1);

// Carousel 组件对于 keep-alive 的组件支持可能有 BUG，会报错，所以 onDeactivated 的时候要隐藏 Carousel 组件
const show = ref(true);

onActivated(() => {
  show.value = true;
});

onDeactivated(() => {
  show.value = false;
});
</script>

<template>
  <section class="page-home-banner">
    <Carousel.Root id="mobile-home-carousel" class="relative h-320 overflow-x-hidden" autoplay loop v-model:page="index" v-if="show && imgList?.length">
      <Carousel.Context v-slot="context">
        <Carousel.ItemGroup>
          <Carousel.Item class="h-320" v-for="(item, idx) in imgList" :key="idx" :index="idx">
            <a class="block size-full" :href="item.jumpUrl" target="_blank" :aria-label="`${$t('mobile.common.carousel.jumpToUrl', { url: item.jumpUrl }) }`">
              <img :src="item.picUrl" :alt="item.operateName" class="block size-full object-cover">
            </a>
          </Carousel.Item>
        </Carousel.ItemGroup>
        <Carousel.IndicatorGroup class="absolute bottom-44 left-50% z-1 mx-auto flex translate-x--50% gap-x-8">
          <Carousel.Indicator
            v-for="(_, idx) in imgList"
            :key="idx"
            :index="idx"
            class="h-3 w-30 rounded-2 bg-[rgb(0,0,0,0.2)]"
            :aria-label="`${$t('mobile.common.carousel.changeTo', { index: idx + 1 }) }`"
            @click="context.play"
          >
            <div
              class="h-full rounded-2 bg-black"
              :class="[ idx === index ? 'w-full transition-width duration-4000 transition-ease-linear' : 'w-0']"
            >
            </div>
          </Carousel.Indicator>
        </Carousel.IndicatorGroup>
      </Carousel.Context>
    </Carousel.Root>
  </section>
</template>

<style lang="scss" scoped>
</style>
